import { defineStore } from "pinia";
import { computed, ref } from "vue";
import type { User } from "../types/User";

export const useLogging = defineStore("logging", () => {
  const user = ref<User>();
  const loggedIn = ref<boolean>(false);

  const getUser = computed(() => user.value);
  const isLoggedIn = computed(() => loggedIn.value);

  function login(userToLogin: User) {
    user.value = userToLogin;
    loggedIn.value = true;
    localStorage.setItem("userId", user.value.id.toString());
  }

  function logout() {
    user.value = undefined;
    loggedIn.value = false;
    localStorage.removeItem("userId");
  }

  function updateFavoriteCount(newCount: number) {
    if (user.value) {
      user.value.favoriteCount = newCount;
    }
  }

  function updateBorrowCount(newCount: number) {
    if (user.value) {
      user.value.borrowCount = newCount;
    }
  }

  return {
    user,
    loggedIn,
    getUser,
    isLoggedIn,
    login,
    logout,
    updateFavoriteCount,
    updateBorrowCount,
  };
});
